package com.senlingspace.system.service.impl;

import com.senlingspace.common.annotation.DataScope;
import com.senlingspace.common.core.domain.AjaxResult;
import com.senlingspace.common.core.domain.entity.SysDept;
import com.senlingspace.common.utils.*;
import com.senlingspace.system.domain.*;
import com.senlingspace.system.domain.dto.ShopResponse;
import com.senlingspace.system.domain.dto.SlkjShopDto;
import com.senlingspace.system.domain.vo.SharesInvestorVo;
import com.senlingspace.system.domain.vo.SharesPosVo;
import com.senlingspace.system.domain.vo.SharesProjectVo;
import com.senlingspace.system.domain.vo.ShopOperateVo;
import com.senlingspace.system.mapper.*;
import com.senlingspace.system.service.ISlkjShopPosService;
import com.senlingspace.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 门店Service业务层处理
 *
 * @author SenlingSpace
 * @date 2024-06-27
 */
@Service
@Slf4j
public class SlkjShopServiceImpl implements ISlkjShopService {
    @Autowired
    private SlkjShopMapper slkjShopMapper;
    @Autowired
    private SlkjShopProjectMapper slkjShopProjectMapper;
    @Autowired
    private SlkjShopPosMapper fzPosMapper;
    @Autowired
    private SlkjShopOperateMapper fzOperateMapper;
    @Autowired
    private SlkjPosMapper posMapper;
    @Autowired
    private SlkjOperateMapper operateMapper;
    @Autowired
    private SlkjFareSchemeShopMapper slkjFareSchemeShopMapper;
    @Autowired
    private ISlkjShopProjectFzService projectFzService;
    @Autowired
    private ISlkjShopInvestorService slkjShopInvestorService;
    @Autowired
    private ISlkjShopPosService shopPosService;
    @Autowired
    private ISlkjShopOperateService operateService;
    @Autowired
    private ISlkTeamStatusService slkTeamStatusService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysAreaMapper sysAreaMapper;


    @Override
    public List<ShopResponse> getShopsByDeptId(Long deptId) {
        if (deptId == null) {
            return new ArrayList<>();
        }
        return slkjShopMapper.selectShopsByDeptIdAndDelFlag(deptId);
    }

    /**
     * 查询门店
     *
     * @param shopId 门店主键
     * @return 门店
     */
    @Override
    public SlkjShop selectSlkjShopByShopId(Long shopId) {
        return slkjShopMapper.selectSlkjShopByShopId(shopId);
    }

    /**
     * 查询门店列表
     *
     * @param slkjShopDto 门店
     * @return 门店
     */
    @DataScope(deptAlias = "s", userAlias = "s")
    @Override
    public List<SlkjShopDto> selectSlkjShopList(SlkjShopDto slkjShopDto) {
        PageUtils.startPage();
        return slkjShopMapper.selectSlkjShopList(slkjShopDto);
    }

    /**
     * 新增门店
     *
     * @param slkjShop 门店
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSlkjShop(SlkjShop slkjShop) {
        SysDept sysDept = new SysDept();
        sysDept.setDeptName(slkjShop.getShopName());
        sysDept.setParentId(0L);
        sysDept.setAncestors("0");
        sysDept.setOrderNum(1);
        sysDept.setLeader(slkjShop.getCountyName());
        sysDept.setPhone(slkjShop.getContactTel());
        sysDept.setCreateBy(SecurityUtils.getUsername());
        sysDept.setCreateTime(DateUtils.getNowDate());
        sysDeptMapper.insertDept(sysDept);
        log.info("新增门店部门数据ID {}", sysDept.getDeptId());

        String countyCode = slkjShop.getCountyCode();
        if (StringUtils.isNotBlank(countyCode)) {
            SysArea area = sysAreaMapper.findAreaById(Long.valueOf(countyCode));
            slkjShop.setCountyName(area.getFullName().replaceAll("，", "/"));
        }

        slkjShop.setDeptId(sysDept.getDeptId());
        slkjShop.setShopNo(NumberGenerator.getCharacters());
        slkjShop.setCreateBy(SecurityUtils.getUsername());
        slkjShop.setUserId(SecurityUtils.getUserId());
        int insertId = slkjShopMapper.insertSlkjShop(slkjShop);
        log.info("新增门店数据ID {}", slkjShop.getShopId());

        SlkjPos slkjPos = posMapper.selectSlkjPos();
        if (slkjPos == null) {
            throw new IllegalArgumentException("请添加pos商");
        }
        SlkjOperate operate = operateMapper.selectSlkjOperate();
        if (operate == null) {
            throw new IllegalArgumentException("请添加运营商");
        }


        SlkjShopPos slkjShopPos = new SlkjShopPos();
        slkjShopPos.setPosId(slkjPos.getPosId());
        slkjShopPos.setShopId(slkjShop.getShopId());
        slkjShopPos.setCreateBy(SecurityUtils.getUsername());
        fzPosMapper.insertSlkjShopPos(slkjShopPos);
        log.info("门店票务关系表添加数据成功");
        SlkjShopOperate slkjShopOperate = new SlkjShopOperate();
        slkjShopOperate.setOperateId(operate.getOperateId());
        slkjShopOperate.setShopId(slkjShop.getShopId());
        slkjShopOperate.setCreateBy(SecurityUtils.getUsername());
        fzOperateMapper.insertSlkjShopOperate(slkjShopOperate);
        log.info("门店运营商关系表添加数据成功");


        Long shopId = slkjShop.getShopId();
        //初始化门店组队信息
        slkTeamStatusService.initByShopId(shopId, 500L);


        return insertId;

    }

    /**
     * 修改门店
     *
     * @param slkjShop 门店
     * @return 结果
     */
    @Override
    public int updateSlkjShop(SlkjShop slkjShop) {
        String shopName = slkjShop.getShopName();
        SysDept dept = sysDeptMapper.selectDeptById(slkjShop.getDeptId());
        dept.setDeptName(shopName);
        dept.setUpdateTime(DateUtils.getNowDate());
        sysDeptMapper.updateDept(dept);
        slkjShop.setUpdateTime(DateUtils.getNowDate());

        String countyCode = slkjShop.getCountyCode();
        if (StringUtils.isNotBlank(countyCode)) {
            SysArea area = sysAreaMapper.findAreaById(Long.valueOf(countyCode));
            slkjShop.setCountyName(area.getFullName().replaceAll("，", "/"));
        }
        return slkjShopMapper.updateSlkjShop(slkjShop);
    }

    /**
     * 批量删除门店
     *
     * @param shopIds 需要删除的门店主键
     * @return 结果
     */
    @Override
    public int deleteSlkjShopByShopIds(Long[] shopIds) {
        return slkjShopMapper.deleteSlkjShopByShopIds(shopIds);
    }

    /**
     * 删除门店信息
     *
     * @param shopId 门店主键
     * @return 结果
     */
    @Override
    public int deleteSlkjShopByShopId(Long shopId) {
        return slkjShopMapper.updateSlkjShopByShopId(shopId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addProject(List<SlkjShopProject> shopProjects) {
        for (SlkjShopProject shopProject : shopProjects) {
            shopProject.setDelFlag((byte) 0);
            shopProject.setCreateTime(new Date());
            slkjShopProjectMapper.insertSlkjShopProject(shopProject);
        }
    }

    @Override
    public void editProject(List<SlkjShopProject> shopProjects) {
        SlkjShopProject sp = new SlkjShopProject();
        sp.setShopId(shopProjects.get(0).getShopId());
        sp.setDelFlag((byte) 1);
        sp.setUpdateTime(new Date());
        slkjShopProjectMapper.updateSlkjShopProjectStatusByShopId(sp);

        for (SlkjShopProject shopProject : shopProjects) {
            shopProject.setDelFlag((byte) 0);
            shopProject.setCreateTime(new Date());
            slkjShopProjectMapper.insertSlkjShopProject(shopProject);
        }
    }

    @Override
    public int updateStatus(String status, Long id) {
        int i = slkjShopMapper.updateStatus(status, id);
        return i;
    }

    @Override
    public AjaxResult existsFareScheme(Long id) {
        SlkjFareSchemeShop fareSchemeShop = new SlkjFareSchemeShop();
        fareSchemeShop.setShopId(id);
        fareSchemeShop.setStatus(0);
        List<SlkjFareSchemeShop> fareSchemeShops = slkjFareSchemeShopMapper.selectSlkjFareSchemeShopList(fareSchemeShop);
        return CollectionUtils.isNotEmpty(fareSchemeShops) ? AjaxResult.success(fareSchemeShops.get(0)) : AjaxResult.success();
    }


    @Override
    public AjaxResult storeListingInformationCheck(Long id) {

        HashMap<String, Boolean> checkList = new HashMap<>();
        //检查 票价 票类 票档是否设置
        SlkjFareSchemeShop fareSchemeShop = new SlkjFareSchemeShop();
        fareSchemeShop.setShopId(id);
        fareSchemeShop.setStatus(0);
        List<SlkjFareSchemeShop> fareSchemeShops = slkjFareSchemeShopMapper.selectSlkjFareSchemeShopList(fareSchemeShop);
        if (CollectionUtils.isNotEmpty(fareSchemeShops)) {
            checkList.put("ticketPrice", true);
        } else {
            checkList.put("ticketPrice", false);
        }
        //检查已关联项目
        List<SharesProjectVo> projectList = projectFzService.selectProjectShopByShopId(id);
        if (CollectionUtils.isNotEmpty(projectList)) {
            checkList.put("Projec", true);
        } else {
            checkList.put("Projec", false);
        }
//        检查已关联投资人
        List<SharesInvestorVo> investorList = slkjShopInvestorService.selectInvestorShopByShopId(id);
        if (CollectionUtils.isNotEmpty(investorList)) {
            checkList.put("Investor", true);
        } else {
            checkList.put("Investor", false);
        }
//      检查是否设置分账
        checkList.put("IndependentAccount", false);
        if (checkList.get("Projec") && checkList.get("Investor")) {
            SharesPosVo pos = shopPosService.selectPosShopByShopId(id);
            ShopOperateVo operate = operateService.selectOperateShopByShopId(id);
            if (pos != null && operate != null) {
                checkList.put("IndependentAccount", true);
            }
        }
        return AjaxResult.success(checkList);
    }
}
